package com.zhaoyu.article.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhaoyu.apis.article.ApAuthorControllerApi;
import com.zhaoyu.article.service.ApAuthorService;
import com.zhaoyu.model.article.pojos.ApAuthor;
import com.zhaoyu.model.common.dtos.ResponseResult;
import com.zhaoyu.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/v1/author")
public class ApAuthorController implements ApAuthorControllerApi {

    @Autowired
    private ApAuthorService apAuthorService;

    @Override
    @GetMapping("/findByUserId/{id}") // rest风格
    public ApAuthor findByUserIdApAuthor(@PathVariable("id") Integer id){
        List<ApAuthor> list = apAuthorService.list(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getUserId, id));
        if (list != null && !list.isEmpty()){ // 如果不为空,则返回第一个
            return list.get(0);
        }
        return null;
    }

    @Override
    @PostMapping("/save") // json格式的数据
    public ResponseResult saveApAuthor(@RequestBody ApAuthor apAuthor){
        apAuthor.setCreatedTime(new Date());
        apAuthorService.save(apAuthor);
        // int i = 1/0; // 测试分布式事务
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    @GetMapping("/findByName/{name}") // rest风格
    public ApAuthor findByNameApAuthor(@PathVariable String name) {
        ApAuthor author = apAuthorService.getOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getName, name));
        return author;
    }

    @Override
    @GetMapping("/findById/{id}") // rest风格
    public ApAuthor findByIdApAuthor(@PathVariable("id") Integer id) {
        return apAuthorService.getById(id);
    }

}